package models;

import java.lang.reflect.Type;
import java.util.List;
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;

import play.db.jpa.Model;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;

@Entity
public class MenuSection extends Model {
	@Column(nullable=false)
	private String name;

	@ManyToOne(fetch=FetchType.LAZY)
	@JoinColumn(name="menu_id", insertable=false, updatable=false)
	private Menu menu;
	
	@OneToMany(cascade=CascadeType.ALL, orphanRemoval=true, fetch=FetchType.LAZY)
	private Set<MenuSection> subSections;
	
	@OneToMany(cascade=CascadeType.ALL, orphanRemoval=true, fetch=FetchType.LAZY)
	@JoinColumn(name="section_id")
	private Set<MenuItem> items;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Menu getMenu() {
		return menu;
	}

	public void setMenu(Menu menu) {
		this.menu = menu;
	}

	public Set<MenuItem> getItems() {
		return items;
	}

	public void setItems(Set<MenuItem> items) {
		this.items = items;
	}

	public Set<MenuSection> getSubSections() {
		return subSections;
	}

	public void setSubSections(Set<MenuSection> subSections) {
		this.subSections = subSections;
	}

	public static class SectionsJsonSerializer implements JsonSerializer<List<MenuSection>> {
		@Override
		public JsonElement serialize(List<MenuSection> sections, Type type,
				JsonSerializationContext context) {

			JsonArray sectionsJson =  new JsonArray();
			SectionJsonSerializer sectionSerializer =  new SectionJsonSerializer();
			
			for (MenuSection section : sections) {
				sectionsJson.add(sectionSerializer.serialize(section, type, context));
			}

			return sectionsJson;
		}
	}

	public static class SectionJsonSerializer implements JsonSerializer<MenuSection> {
		@Override
		public JsonElement serialize(MenuSection section, Type type,
				JsonSerializationContext context) {
			JsonObject sectionJson = new JsonObject();
			
			sectionJson.addProperty("id", section.getId());
			sectionJson.addProperty("name", section.getName());

			return sectionJson;
		}
	}
}
